<?php

namespace App\Services\Dao;

use App\Constants\CommonCode;

class BaseDao
{

    /**
     * note:查询数据
     * @param array $conditions
     * @param array|string[] $columns
     * @param array $relatives
     * created by: lhw at 13/1/2022 10:25 下午
     * @return mixed
     */
    public function fetchData(array $conditions, array $columns = ['*'], $relatives = [])
    {
        $model = $this->filterConditions($this->getModel(), $conditions);
        return $this->fetchDetailRows($model, $conditions, $columns, $relatives);
    }

    /**
     * note:查询具体数据
     * @param $model
     * @param array $conditions
     * @param array|string[] $columns
     * @param array $relatives
     * created by: lhw at 13/1/2022 10:25 下午
     * @return mixed
     */
    public function fetchDetailRows($model, array $conditions, array $columns = ['*'] , array $relatives = [])
    {
        //排序
        if (isset($conditions['sortColumns']) && is_array($conditions['sortColumns'])) {
            foreach ($conditions['sortColumns'] as $column) {
                if ($column['sort'] == CommonCode::MODEL_SORT_DESC) {
                    $model = $model->orderByDesc($column['sortColumn']);
                } else {
                    $model = $model->orderBy($column['sortColumn']);
                }
            }
        }

        //获取数据
        if (!empty($conditions['all']) && $conditions['all'] == 'true') {
            $model = $model->get($columns);
        } elseif (isset($conditions['limit'])) {
            $model = $model->take((int)$conditions['limit'])->get($columns);
        } elseif (isset($conditions['first']) && $conditions['first'] == 'true') {
            $model = $model->first($columns);
        } elseif (isset($conditions['count']) && $conditions['count'] == 'true') {
            $model = $model->count();
        } else {
            $model = $model->paginate(
                $conditions['pageSize'] ?? 10,
                $columns,
                'page',
                !empty($conditions['page']) ? $conditions['page'] : null
            );
        }

        //加载关联对象
        if ($model && !empty($relatives)) {
            $model->load($relatives);
        }

        return $model;
    }
}
